# Create your views here.
#coding:utf-8
import os
from django.conf import settings
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate,login as auth_login,logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from wall.models import *
from bookwall.models import *
from accounts.models import UserMessage
from models import *
from forms import *
from PIL import Image
from bookwall.doubanbook import DBbook

def wall(request):
    walllist = WallList.objects.all()
    return render_to_response("wall.html",{"walllist":walllist},RequestContext(request))

def new_thing(request):
    form = NewthingForm()
    if request.method == "POST":
        form = NewthingForm(request.POST,request.FILES)
        if form.is_valid():
            detailtype = form.cleaned_data['detailtype']
            if detailtype == "1":
                detailisbn = form.cleaned_data['detailisbn']
                return HttpResponseRedirect(reverse('book_had',args = (str(detailisbn),)))
            detailname = form.cleaned_data['detailname']
            detailnote = form.cleaned_data['detailnote']
            wallkind = WallKind.objects.get(pk = int(detailtype))
            walllist = WallList.objects.create(comments_num = 0,wallkind = wallkind, user = request.user)
            walllist.title = detailname
            walllist.content = detailnote
            walllist.save()
            if "detailpic" in request.FILES:
                print "a"
                detailpic = request.FILES['detailpic']
                extention  = os.path.splitext(detailpic.name)[1]
                img = Image.open(detailpic)
                img.name = str(walllist.id) + extention 
                url = "wall/" + img.name
                name = settings.MEDIA_ROOT + "/" + url
                img.save(name,"jpeg")
                walllist.img = url
                walllist.save() 

            return HttpResponseRedirect(reverse("wall_info",args=(walllist.id,)))
    return render_to_response("new_things.html",{"form" : form},RequestContext(request))

def wall_info(request,wallid):
    try:
        del request.session['notifications']
    except:
        pass
    wall = WallList.objects.get(pk = int(wallid))
    book = None
    if wall.wallkind.id == 1:
        book = BookExchangeList.objects.get(wall = wall).book
    comments = None
    try:
        comments = WallComments.objects.filter(wall = wall)
    except:
        pass
    form = CommentForm()
    if request.method == "POST":
        form = CommentForm(request.POST.copy())
        if form.is_valid():
            replynote = form.cleaned_data['replynote']
            comment = WallComments.objects.create(wall = wall,user = request.user)
            comment.content = replynote
            comment.save()
            wall.comments_num += 1
            wall.save()
            if not request.user == wall.user:
                try:
                    
                    usermessage = UserMessage.objects.get(user = wall.user,message_kind = 3,detail_id = int(wall.id),isviewed = False)
                except:

                    usermessage = UserMessage.objects.create(user = wall.user,message_kind = 3,detail_id = int(wall.id),isviewed = False)
                    usermessage.save()

            return HttpResponseRedirect(reverse("wall_info",args = (wall.id,)))
    return render_to_response("wallinfo.html",{"wall":wall,"form":form,"comments":comments,"user":request.user,"book":book},RequestContext(request))

def book_had(request,isbn):
    db = DBbook(isbn)
    db.getXML()
    if db.xml:
        request.session['dbbook'] = db
        return render_to_response("newbook1.html",{"db":db,"book":None},RequestContext(request))
    else:
        try:
            book = BookWall.objects.get(isbn = isbn)
            request.session['book'] = book
            return render_to_response("newbook1.html",{"db":None,"book":book},RequestContext(request))
        except:
            try:
                del request.session['dbbook']
            except:
                pass
            try:
                del request.session['book']
            except:
                pass
            request.session['isbn'] = isbn
            return HttpResponseRedirect(reverse('new_book'))

